package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author : Sonic
 * @version : 1.0
 * @createTime : 2024-11-29  20:42
 * @description :
 */

@Slf4j
@RestController
@RequestMapping("/admin/common")
@Api(tags = "Common Api")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * @param: [file]
     * @return: com.sky.result.Result<java.lang.String>
     * @description: upload file to aliyun oss
     **/
    @PostMapping("/upload")
    @ApiOperation("upload file")
    public Result<String> upload(MultipartFile file) { // file与前端传过来的参数名一致
        try {
            String originalFilename = file.getOriginalFilename();
            String extendFileName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID() + extendFileName;
            String url = aliOssUtil.upload(file.getBytes(), fileName);
            return Result.success(url);
        } catch (IOException e) {
            log.info("###### upload file loss: {}", e.getMessage());
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
